package com.jtw.common.util;

import lombok.extern.slf4j.Slf4j;
import org.joda.time.LocalDateTime;

import javax.swing.*;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.security.CodeSource;

/**
 * DESCRIPT: 备份工具
 *
 * @author cjsky666
 * @date 2019/3/18 13:05
 */
@Slf4j
public class backupUtil {
    /**
     * 判断系统是否是windows
     * @return
     */
    public static boolean isWindows(){
        String os = System.getProperty("os.name");
        if(os.toLowerCase().startsWith("win")){
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }

    public static void backDataBase(String hostIP, String user, String pwd, String dbName,String filePath) {
        File file = new File(filePath);
        if(!file.exists()){
            file.mkdirs();
        }
        String savePath = filePath + DateUtil.format(LocalDateTime.now().toDate(),"yyyyMMddmmhhss") + ".sql";

        String cmd = "mysqldump " + " -u " + user + " -p" + pwd + " " + dbName + " > " + savePath;
        Process process = null;
        System.out.println(cmd);
        try {
            if(isWindows()){
                process = Runtime.getRuntime().exec(new String[]{"cmd.exe","/c",cmd});
            }else{
                Runtime.getRuntime().exec(new String[]{"/bin/sh ","-c ",cmd});
            }
            int processComplete = 0;
            processComplete = process.waitFor();
            if (processComplete == 0) {
                log.info("备份数据库 "+dbName+" success");
            } else {
                log.error("备份数据库 "+dbName+" success");
            }
        } catch (InterruptedException | IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        backDataBase(
                "localhost",
                "root",
                "123456",
                "test",
                "/mm/");
    }

}
